package com.mehdiuz.backend.commons.config;

import com.mehdiuz.backend.commons.handler.CustomTokenFilter;
import com.mehdiuz.backend.commons.property.CustomPasswordEncoder;
import com.mehdiuz.backend.role.service.impl.UserDetailsServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private CustomTokenFilter customTokenFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 这是配置的关键，决定哪些接口开启防护，哪些接口绕过防护
        http
                //关闭csrf
                .csrf().disable()
                // 开启跨域以便前端调用接口
                .cors()
                .and().authorizeRequests()
                // 指定某些接口不需要通过验证即可访问。登陆接口肯定是不需要认证的
                .antMatchers("/admin/system/index/login").anonymous()
                .antMatchers("/api/captcha/pullCaptcha","/api/captcha/checkCaptcha").anonymous()
                // 这里意思是其它所有接口需要认证才能访问
                .anyRequest().authenticated()
                .and().addFilterBefore(customTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //禁用session
        http.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
    }

    @Autowired
    private UserDetailsServiceImpl UserDetailsServiceImpl;

    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        //返回authenticationManger，在编写登录功能时需要进行认证
        return super.authenticationManagerBean();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        //配置使用自定义的userDetailsService和自定义的passwordEncoder
        auth.userDetailsService(UserDetailsServiceImpl).passwordEncoder(passwordEncoder);
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        //将自定义的passwordEncoder放入ioc容器
        return new CustomPasswordEncoder();
    }
}
